from flask import Blueprint, request
from flask_jwt_extended import jwt_required, get_jwt_identity

from model.user_model import UserModel
from service.user_service import UserService

user_router = Blueprint(name="user", import_name=__name__)
user_service = UserService()


@user_router.route("/user/get_info")
@jwt_required()
def user_get_info():
    """
    获取用户信息
    :return:
    """
    # 获取JWT中的用户身份（这通常是一个用户ID）
    user_identity = get_jwt_identity()
    return {"code": 0, "msg": "get user success", "data": user_identity.get('username')}


@user_router.route("/user/get")
def user_get():
    """
    用户列表
    :return:
    """
    # 则返回全部数据
    datas = [user.as_dict() for user in user_service.list()]
    return {"code": 0, "msg": "get users success", "data": datas}


@user_router.route("/user/register", methods=["POST"])
def user_register():
    """
    用户的注册
    {
        "username":xxx,
        "password":xxx,
    }
    :return:
    """
    # 获取请求体
    data = request.json
    # 构建用户对象
    user = UserModel(**data)
    print(user.password)
    if user:
        user_id = user_service.create(user)
        if user_id:
            # 存在id,则证明新增成功了
            return {"code": 0, "msg": "注册成功"}
        else:
            return {"code": 40001, "msg": "注册失败"}
    return {"code": 40001, "msg": "注册失败"}


@user_router.route("/user/login", methods=["POST"])
def user_login():
    """
    用户的登录
    {
        "username":xxx,
        "password":xxx,
    }
    :return:
    """
    # 获取请求体
    data = request.json
    # 构建用户对象
    user = UserModel(**data)
    # 通过用户名查找用户是否存在
    user_result = user_service.get_by_name(user.username)
    print(user_result)
    print(data.get("password"))
    # 如果用户不存在，说明用户还未注册
    if not user_result:
        return {"code": 40013, "msg": "登录失败"}
    # 如果密码不匹配，说明密码错误
    if not user_result.check_hash_password(data.get("password")):
        return {"code": 40014, "msg": "登录失败"}
    # 用户存在，且密码匹配，则生成 token
    access_token = user_service.create_access_token(user_result)
    print(access_token)
    if access_token:
        # 存在access_token,则证明登录成功了
        return {"code": 0, "msg": "登录成功", "data": {"token": access_token}}
    else:
        return {"code": 40021, "msg": "登录失败"}
